#import <CoreFoundation/CoreFoundation.h>
#import <Foundation/Foundation.h>
//#import <Foundation/NSBundle.h>
//#import <UIKit/UIWindow.h>
#import <UIKit/UIKit.h>
//#import <UIKit/UIApplication.h>
//#import <UIKit/UITextView.h>
//#import <UIKit/UITableView.h>
//#import <UIKit/UINavigationBar.h>
//#import <UIKit/UIView.h>
//#import <Foundation/NSFileManager.h>
//#import <UIKit/UIAlert.h>
//#import <Foundation/NSString.h>
//#import <UIKit/UIProgressView.h>
//#import <UIKit/UIBarButtonItem.h>
//#import "NSTask.h"
//#import <Foundation/NSURL.h>
//#import <UIKit/UITextInputTraits.h>
//#import <UIKit/UIDevice.h>

const NSString * defaultPath = @"/var/mobile/Library/Caches/";
const NSString * defaultMapTiles_old = @"/var/mobile/Library/Caches/MapTiles/MapTiles.sqlitedb"; // for 2.X & 3.0
const NSString * defaultMapTiles_new = @"/var/mobile/Library/Caches/Maps/MapTiles/MapTiles.sqlitedb"; // for 3.1 ~3.X
const NSString * defaultMapPoint = @"/var/mobile/Library/Preferences/com.apple.Maps.plist";
const NSString * defaultRoute_2_1 = @"/var/mobile/Library/Maps/Routes.plist"; // for 2.1
const NSString * defaultRoute_2_2 = @"/var/mobile/Library/Maps/Directions.plist"; // for 2.2 & 3.0
const NSString * defaultBookmark = @"/var/mobile/Library/Maps/Bookmarks.plist";
const NSString * defaultHistory = @"/var/mobile/Library/Maps/History.plist";
const NSString * iconPath = @"/Applications/offlinemap.app/%@";
const NSString * iconBookmarks = @"Bookmarks.png";
const NSString * iconClear = @"Clear.png";
const NSString * iconHelp = @"Help.png";
const NSString * iconIcon = @"Icon-Small.png";
const NSString * iconImport = @"Import.png";
const NSString * iconMaps = @"Maps.png";
const NSString * iconRoutes = @"Routes.png";
const NSString * iconBookmarks_Clear = @"Bookmarks_Clear.png";
const NSString * iconBookmarks_Import = @"Bookmarks_Import.png";
const NSString * iconMaps_Clear = @"Maps_Clear.png";
const NSString * iconMaps_Import = @"Maps_Import.png";
const NSString * iconRoutes_Clear = @"Routes_Clear.png";
const NSString * iconRoutes_Import = @"Routes_Import.png";
const NSString * homeFolder = @"/var/mobile/Media/Maps";

//Extended from OS3.0 Class-dump
@class UITextField, UILabel;
@interface UIAlertView (Extended)
	- (UITextField*)addTextFieldWithValue:(NSString*)value label:(NSString*)label;
	- (UITextField*)textFieldAtIndex:(NSUInteger)index;
	- (NSUInteger)textFieldCount;
	- (UITextField*)textField;
@end
@interface UIApplication (Extended)
	//- (BOOL)launchApplicationWithIdentifier:(id)fp8 suspended:(BOOL)fp12;
	- (BOOL)launchApplicationWithIdentifier:(NSString*)identifier suspended:(BOOL)flag;
	- (void)setApplicationBadgeString:(id)fp8;
	- (int)applicationIconBadgeNumber;
	- (void)setApplicationIconBadgeNumber:(int)fp8;
@end

@interface UITableView (Extended)
	- (void) setAllowsSelectionDuringEditing:(BOOL) fp8;
@end

@interface Atlas : UIApplication < UITableViewDataSource,UITableViewDelegate >
{
	    UIView            *mainView;
	    UIWindow          *window;
	    UITableView       *table;
	    UINavigationBar   *navbar;
		UINavigationItem  *navtitle;
	    NSMutableArray    *list;
	    NSFileManager     *manager;
	    UIAlertView       *alert,*importAlert,*confirmAlert,*informationAlert,*launchAlert;
	    NSString          *deviceInfo;
	    NSString          *defaultRoute;
	    NSString	      *defaultMapTiles;
}

@end

static NSString * MapTiles  = @"MapTiles.sqlitedb";
static NSString * Plist  = @"com.apple.Maps.plist";
static NSString * HOME  = @"/var/mobile/Media/Maps";
//NSLocalizedString

int main(int argc, char *argv[]) {
    
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    int retVal = UIApplicationMain(argc, argv, @"Atlas", @"Atlas");
    [pool release];
    return retVal;
}


@implementation Atlas

- (void) dealloc{
    [window release];
    [mainView release];
    [table release];
    [navbar release];
    [list release];
    [super dealloc];
}

NSString *SizeString(double size) {
    bool negative = size < 0;
    if (negative)
		size = -size;
    unsigned power = 0;
    while (size > 1024) {
        size /= 1024;
        ++power;
    }
    static const char *powers_[] = {"B", "kB", "MB", "GB"};
    return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
}

- (void) startEditing{
	[table setEditing: YES animated: YES];
	navtitle.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone  target:self  action:@selector(stopEditing)] autorelease];
}

- (void) stopEditing{
	[table setEditing:NO animated:YES];
	navtitle.rightBarButtonItem=[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit  target:self  action:@selector(startEditing)] autorelease];
}

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
	//NSLog(@"[%@ numberOfSectionsInTableView:%@]", [self class], tableView);
	return [list count];
}

- (NSInteger) tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {
    return [[list objectAtIndex:section] count];
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	//NSLog(@"[%@ tableView:%@ cellForRowAtIndexPath:%@]", [self class], tableView, indexPath);
    UITableViewCell *cell = [[[UITableViewCell alloc] initWithFrame: CGRectMake(0.0f, 0.0f, 0.0f, 0.0f)] autorelease];
	NSInteger row = [indexPath row];
	NSInteger section = [indexPath section];
	NSInteger _row = [[list objectAtIndex:section] count];
	NSString *Lable = [[list objectAtIndex:section] objectAtIndex: row];
	NSString *icon ;
	//if([Lable hasSuffix:"plist"])
	Lable = [Lable stringByDeletingPathExtension];
	//NSLog(@"%@ , %@",Lable , [Lable stringByDeletingPathExtension]);
	if(section == ([list count] -1 )) //若是最後一個section，那麼就是關於與說明
	{
		[cell setText: NSLocalizedString( Lable , @"About & Web-Site") ];
		if (row == 0)
			icon = [NSString stringWithFormat:iconPath ,iconIcon];
		else
			icon = [NSString stringWithFormat:iconPath ,iconHelp];
	}
	else
	{
		if (row > ( _row - 3 )){ // 最後一個item是import選項, 倒數第二個是Remove選項
			[cell setText: NSLocalizedString( Lable , @"Import or Remove option") ];
			if(row == (_row -1)) // 最後一個是import
				switch(section){
					case 0:
						icon = [NSString stringWithFormat:iconPath ,iconMaps_Import];
						break;
					case 1:
						icon = [NSString stringWithFormat:iconPath ,iconRoutes_Import];
						break;
					case 2:
						icon = [NSString stringWithFormat:iconPath ,iconBookmarks_Import];
						break;
				}
			else
				switch(section){
					case 0:
						icon = [NSString stringWithFormat:iconPath ,iconMaps_Clear];
						break;
					case 1:
						icon = [NSString stringWithFormat:iconPath ,iconRoutes_Clear];
						break;
					case 2:
						icon = [NSString stringWithFormat:iconPath ,iconBookmarks_Clear];
						break;
				}
		}
		else{
			[cell setText: Lable ];
			switch(section){
				case 0: 
					icon = [NSString stringWithFormat:iconPath ,iconMaps];
					break;
				case 1:
					icon = [NSString stringWithFormat:iconPath ,iconRoutes];
					break;
				case 2: 
					icon = [NSString stringWithFormat:iconPath ,iconBookmarks];
					break;
			}
			
			//cell.image = [UIImage imageWithContentsOfFile:icon];
		}
		
	}
	//NSLog(@"%@ from %@",icon , Lable);
	cell.image = [UIImage imageWithContentsOfFile:icon];
    return cell;
}
/*
- (void)tableView:(UITableView *)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath{
	
	
}
*/
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	//NSLog(@"[%@ tableView:%@ titleForHeaderInSection:%d]", [self class], tableView, section);
	return [[NSArray arrayWithObjects:NSLocalizedString(@"Maps",@"Map section"),NSLocalizedString(@"Routes",@"Route section"),NSLocalizedString(@"Bookmarks",@"Bookmark section"),@"",nil] objectAtIndex: section]; 
}
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
	if (section == 3)
		return [NSString stringWithFormat:NSLocalizedString(@"About_Message",@"for about"),@" version 4.0.4"];
	else
		return @"";
}
- (void) tableView:(UITableView *) tableView didSelectRowAtIndexPath:(NSIndexPath *) indexPath{
	//NSLog(@"[%@ tableView:%@ didSelectRowAtIndexPath:%@]", [self class], tableView, indexPath);
	NSInteger row = [indexPath row];
	NSInteger section = [indexPath section];
	NSString * source = [[list objectAtIndex: section] objectAtIndex: row]; // path must be add /var/mobile/Media/Maps/
	NSString * sourcePath = [NSString stringWithFormat:@"/var/mobile/Media/Maps/%@",source];
    importAlert = [[UIAlertView alloc] initWithTitle: @""
							message: @""
							delegate: self
							cancelButtonTitle: NSLocalizedString(@"Cancel",@"Cancel")
							otherButtonTitles: nil];
	[importAlert addTextFieldWithValue:@"" label:@"Enter Name"];
	[[importAlert textFieldAtIndex:0] becomeFirstResponder];
	alert = [UIAlertView alloc];	
	confirmAlert = [UIAlertView alloc];
	launchAlert  = [UIAlertView alloc];
	switch (section){
		case 0: // maps
			NSLog(@"In Map section");
			if ([source isEqualToString: @"Remove_Map"]){
				NSLog(@"    Remove Cache");
				[[confirmAlert initWithTitle: NSLocalizedString(@"Processing_Command",@"Remove Map")
										message: [NSString stringWithFormat:NSLocalizedString(@"Processing_Command_Message",@"Are you sure to :\n %s ?"), NSLocalizedString(@"Remove_Map",@"Unload Map cache")]
										delegate: self 
										cancelButtonTitle:NSLocalizedString(@"Cancel",@"Cancel")
										otherButtonTitles:NSLocalizedString(@"Yes",@"Yes"),nil] show];
				[self setApplicationBadgeString: @""];
			}
			else if ([source isEqualToString: @"item_Map_Import"]){
				if (![manager fileExistsAtPath:defaultMapTiles]){
					NSLog(@"    Map not Exists");
					[[alert initWithTitle:NSLocalizedString(@"Failed_Import_Map",@"Map not exist")
								message:NSLocalizedString(@"Failed_Import_Map_Message",@"Wrong message")
								delegate:self
								cancelButtonTitle:NSLocalizedString(@"Ok",@"Ok")
								otherButtonTitles:nil]  show];
				}
				else
				{// Maptiles exists , so import alert show
					NSLog(@"    Get name for import Map");
					[importAlert setTitle:NSLocalizedString(@"Import_Map",@"Importing google map cache")];
					[importAlert setMessage:NSLocalizedString(@"Import_Map_Message",@"give a text")];
					[[importAlert textField] setText:@"Untitled"];
					[importAlert addButtonWithTitle:NSLocalizedString(@"item_Map_Import",@"Import ")];
					[importAlert show];
				}
			}
			else if([manager fileExistsAtPath:sourcePath]){
				NSDictionary * mapInfo = [manager attributesOfItemAtPath:[sourcePath stringByAppendingPathComponent:MapTiles] error: nil];
				NSNumber * size = [NSNumber numberWithUnsignedLongLong:[mapInfo fileSize]];
				NSString *sizeString = SizeString([size doubleValue]);
				NSLog([NSString stringWithFormat:@"   Confirm Using Map %@",source]);
					[[confirmAlert initWithTitle: NSLocalizedString(@"Processing_Map",@"Processing Map")
									message: [NSString stringWithFormat:NSLocalizedString(@"Processing_Map_Message",@"Select the method you want\nto use for %@ (%@)"),source,sizeString ]
									delegate: self 
									cancelButtonTitle:NSLocalizedString(@"Cancel",@"Cancel")
									otherButtonTitles:NSLocalizedString(@"Copy",@"Copy"),nil] show];
			}
		
			break;
		case 1: 
			NSLog(@"In Route section");
			if ([source isEqualToString: @"Remove_Route"])
			{
				NSLog(@"    Remove Route");
				[[confirmAlert initWithTitle: NSLocalizedString(@"Remove_Route",@"Remove google map route cache")
									message: [NSString stringWithFormat:NSLocalizedString(@"Processing_Command_Message",@"Are you sure to :\n %@ ?"), NSLocalizedString(@"Remove_Route",@"Remove google map route cache") ]
									delegate: self 
									cancelButtonTitle:NSLocalizedString(@"Cancel",@"Cancel")
									otherButtonTitles:NSLocalizedString(@"Yes",@"Yes"),nil] show];
			}
			else if([source isEqualToString:@"item_Route_Import"]){
				if(![manager fileExistsAtPath:defaultRoute]){
					NSLog(@"    Route Not Exists");
					[[alert initWithTitle:NSLocalizedString(@"Failed_Import_Route",@"Route not exists")
								message:NSLocalizedString(@"Failed_Import_Route_Message",@"ask user to make one first")
								delegate:self
								cancelButtonTitle:NSLocalizedString(@"Ok",@"Ok")
								otherButtonTitles:nil] show];
				}else{
					NSLog(@"    Import Route");
					[importAlert setTitle:NSLocalizedString(@"Import_Route",@"Importing google route cache")];
					[importAlert setMessage:NSLocalizedString(@"Import_Route_Message",@"giva a name for route")];
					[[importAlert textField] setText:@"Untitled"];
					[importAlert addButtonWithTitle:NSLocalizedString(@"item_Route_Import",@"Import ")];
					[importAlert show];
				}
			}
			else{
				NSLog([NSString stringWithFormat:@"    Confirm Using Route %@",source]);
				[[confirmAlert initWithTitle: NSLocalizedString(@"Processing_Route",@"copy Route")
							message: [NSString stringWithFormat:NSLocalizedString(@"Processing_Route_Message","Copy %s"), source]
							delegate: self 
							cancelButtonTitle:NSLocalizedString(@"Cancel",@"Cancel")
							otherButtonTitles:NSLocalizedString(@"Ok",@"Ok"),nil] show];
			}
			break;
		case 2: 
			NSLog(@"In Bookmark section");
			if ([source isEqualToString:@"Remove_Bookmark"]){
				NSLog(@"   Remove Bookmark");
				[[confirmAlert initWithTitle: NSLocalizedString(@"Remove_Bookmark",@"Remove google bookmark cache")
							message: [NSString stringWithFormat:NSLocalizedString(@"Processing_Command_Message",@"Are you sure to :\n %@ ?"), NSLocalizedString(@"Remove_Bookmark",@"Remove google bookmark cache")]
							delegate: self
							cancelButtonTitle:NSLocalizedString(@"Cancel",@"Cancel")
							otherButtonTitles:NSLocalizedString(@"Yes",@"Yes"),nil] show];
			}
			else if([source isEqualToString:@"item_Bookmarks_Import"]) {
				if(![manager fileExistsAtPath:defaultBookmark]){
					NSLog(@"   Bookmark Not Exists");
					[[alert initWithTitle:NSLocalizedString(@"Failed_Import_Bookmarks",@"Bookmark not exists")
								message:NSLocalizedString(@"Failed_Import_Bookmarks_Message",@"ask user to make one first")
								delegate:self
								cancelButtonTitle:NSLocalizedString(@"Ok",@"Ok")
								otherButtonTitles:nil] show];
				}else{
					NSLog(@"   Importing BookMark");
					[importAlert setTitle:NSLocalizedString(@"Import_Bookmarks",@"Importing google bookmark cache")];
					[importAlert setMessage:NSLocalizedString(@"Import_Bookmarks_Message",@"Importing google bookmark message")];
					[[importAlert textField] setText:@"Untitled"];
					[importAlert addButtonWithTitle:NSLocalizedString(@"item_Bookmarks_Import",@"Import ")];
					[importAlert show];
				}
			}
			else{
				NSLog([NSString stringWithFormat:@"   Comfirm  Using BookMark %@  " , source]);
				[[confirmAlert initWithTitle: NSLocalizedString(@"Processing_Bookmarks",@"Copy bookmark")
							message: [NSString stringWithFormat:NSLocalizedString(@"Processing_Bookmarks_Message", @"Copy %s"), source]
							delegate: self
							cancelButtonTitle:NSLocalizedString(@"Cancel",@"Cancel")
							otherButtonTitles:NSLocalizedString(@"Ok",@"Ok"),nil] show];
			}
			break;
		case 3:
			NSLog(@"In Instruction section");
			switch(row){
				case 0:
					NSLog(@"  Show Instruction message");
					informationAlert = [[UIAlertView alloc] initWithTitle: NSLocalizedString(@"Instructions",@"Atlas instructions")
											message: NSLocalizedString(@"Instructions_Message",@"Atlas instructions message")
											delegate: self
											cancelButtonTitle:NSLocalizedString(@"Ok",@"Ok")
											otherButtonTitles:nil];
					[informationAlert show];
					break;
				case 1:
					NSLog(@"  Launch Safari to show main site");
					[[launchAlert initWithTitle:NSLocalizedString(@"Launch_Safari",@"call safari")
												message:NSLocalizedString(@"Launch_Safari_Message",@"visit our main site")
												delegate:self
												cancelButtonTitle:NSLocalizedString(@"Cancel",@"Cancel")
												otherButtonTitles:NSLocalizedString(@"Web_Site",@"call safari"),nil] show];
					break;
			}
			break;
	}
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
	NSInteger row = [indexPath row];
	NSInteger section = [indexPath section];
	if(table.editing){
		if(section <= 2){
			if(row < ([[list objectAtIndex:section] count] - 2))
				return UITableViewCellEditingStyleDelete;
			else
				return UITableViewCellEditingStyleNone;
		}
	}
	return UITableViewCellEditingStyleNone;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
		//NSInteger row = [indexPath row];
		//NSInteger section = [indexPath section];
		//NSString *Name = [[list objectAtIndex:section] objectAtIndex:row];
	//NSLog(@"call remove at %@",[[list objectAtIndex:section] objectAtIndex:row]);
	if(editingStyle == UITableViewCellEditingStyleDelete) {
		/*
		[table beginUpdates];
		switch(section){
			case 0:
				if ([manager fileExistsAtPath: [NSString stringWithFormat:@"/var/mobile/Media/Maps/%@/%@",Name,MapTiles]] && [manager fileExistsAtPath: [NSString stringWithFormat:@"/var/mobile/Media/Maps/%@/%@",Name,Plist]]){
					//[manager removeItemAtPath: [NSString stringWithFormat:@"/var/mobile/Media/Maps/%@/%@",Name,MapTiles] error:nil];
					//[manager removeItemAtPath: [NSString stringWithFormat:@"/var/mobile/Media/Maps/%@/%@",Name,Plist] error:nil];
					[manager removeItemAtPath: [NSString stringWithFormat:@"/var/mobile/Media/Maps/%@",Name] error:nil];
					NSLog([NSString stringWithFormat:@"/var/mobile/Media/Maps/%@ is remove",Name]);
					[[list objectAtIndex:section] removeObjectAtIndex:row];
					[table deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]  withRowAnimation:UITableViewRowAnimationFade];
				}
				break;
			case 1:
			case 2:
				if ([manager fileExistsAtPath: [NSString stringWithFormat:@"/var/mobile/Media/Maps/%@",Name]]){
					[manager removeItemAtPath: [NSString stringWithFormat:@"/var/mobile/Media/Maps/%@",Name] error:nil];
					NSLog([NSString stringWithFormat:@"/var/mobile/Media/Maps/%@ is remove",Name]);
					[[list objectAtIndex:section] removeObjectAtIndex:row];
					[table deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]  withRowAnimation:UITableViewRowAnimationFade];
				}
				break;
			default:
				break;
		}
		[table endUpdates];
		[table reloadData];
		//[table deleteRowsAtIndexPaths: indexPath withRowAnimation:UITableViewRowAnimationFade];
		//self.stopEditing ;
		*/
		NSString *itemName = [[list objectAtIndex:[indexPath section]] objectAtIndex:[indexPath row]];
		NSLog([NSString stringWithFormat:@"Prepare remove item %@ at %i of %i",itemName , [indexPath section] , [indexPath row]]);
		if ([manager fileExistsAtPath:[NSString stringWithFormat:@"%@/%@",homeFolder, itemName ]]) {
			[manager removeItemAtPath:[NSString stringWithFormat:@"%@/%@",homeFolder, itemName ] error:nil];
			NSLog([NSString stringWithFormat:@"Delete Map item %@",itemName]);
			[[list objectAtIndex:[indexPath section] ] removeObjectAtIndex:[indexPath row]];
			[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
		}
	}
	//else if (editingStyle == UITableViewCellEditingStyleInsert) {
	        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
	//}
}


- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
	return (table.isEditing);
}

- (void) alertView:(UIAlertView *) alertView clickedButtonAtIndex: (NSInteger) buttonIndex{
	//NSLog(@"[%@ alertView:%@ clickedButtonAtIndex:%d]", [self class], alertView, buttonIndex);
	NSIndexPath *index = [table indexPathForSelectedRow];
	NSInteger row = [index row];
	NSInteger section = [index section];
	NSString *Name;
	NSString *title,*message;
	UIAlertView *a = [[UIAlertView alloc] autorelease];
	if (buttonIndex == 0){
		NSLog(@"    Cancel button or Ok button");
		//[alertView release];
		return;
	}
	if (alertView == importAlert){
		NSLog(@"in Import Alert");
		Name = [alertView textField].text;
		if( [Name isEqualToString:@""]){
			NSLog(@"    Blank input text");
			[[a initWithTitle:NSLocalizedString(@"blank_name",@"When user enter a empty text") 
				message:NSLocalizedString(@"blank_name_Message",@"Wrong message") 
				delegate:self 
				cancelButtonTitle:NSLocalizedString(@"Ok",@"Ok") 
				otherButtonTitles:nil] show];
			return;
		}
		else{
			NSLog([NSString stringWithFormat:@"    importing %@ ", Name]);
			if (section == 1 || section == 2){ // route bookmark add a plist extension
				if (![[[Name pathExtension] lowercaseString] isEqualToString:@"plist"]){
					Name = [Name stringByAppendingPathExtension:@"plist"];
				}
			}
			if ( [manager fileExistsAtPath:[NSString stringWithFormat:@"/var/mobile/Media/Maps/%@",Name] ]){
				NSLog([NSString stringWithFormat:@"    file Name %@ already exists in /var/mobile/Media/Maps/", Name]);
				switch(section){
					case 0:
						title 	= NSLocalizedString(@"Map_exists",@"Map folder already exist");
						message = NSLocalizedString(@"Map_exists_Message",@"Wrong message");
						break;
					case 1:
						title 	= NSLocalizedString(@"Route_exists",@"Route file name in used");
						message = NSLocalizedString(@"Route_exists_Message",@"Wrong message");
						break;
					case 2:
						title 	= NSLocalizedString(@"Bookmarks_exists",@"Bookmark file name in used");
						message = NSLocalizedString(@"Bookmarks_exists_Message",@"Wrong message");
						break;
					case 3:
						//impossible...
						break;
				}
				[[a initWithTitle:title
					message:[NSString stringWithFormat:message,Name]
					delegate:self 
					cancelButtonTitle:NSLocalizedString(@"Ok",@"Ok") 
					otherButtonTitles:nil] show];
				return;
			}
			else{
				switch(section){
					case 0:
						NSLog(@"  in import Map function");
						if([manager fileExistsAtPath:defaultMapTiles] && [manager fileExistsAtPath:defaultMapPoint]){
							NSLog(@"    Making folder:");
							NSString *folder = [NSString stringWithFormat:@"/var/mobile/Media/Maps/%@", Name ]; 
							NSLog( @"%@",folder);
							NSLog(@"Creat Directiory");
							[manager createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:nil error:nil];
							NSLog(@"Move item");
							[manager moveItemAtPath: defaultMapTiles toPath: [folder stringByAppendingPathComponent: MapTiles ] error:nil];
							[manager moveItemAtPath: defaultMapPoint toPath: [folder stringByAppendingPathComponent: Plist ] error:nil];
							NSLog(@"Make a Duprecate");
							[manager copyItemAtPath:[folder stringByAppendingPathComponent: Plist ] toPath:defaultMapPoint error:nil];
							//[manager createSymbolicLinkAtPath:defaultMapTiles withDestinationPath: [folder stringByAppendingPathComponent:MapTiles] error: nil];
							[manager copyItemAtPath:[folder stringByAppendingPathComponent: MapTiles ] toPath:defaultMapTiles error:nil];
							//NSLog(@"Finished");
							[[list objectAtIndex:0] removeLastObject];
							[[list objectAtIndex:0] removeLastObject];
							[[list objectAtIndex:0] addObject:Name];
							[[list objectAtIndex:0] addObject:@"Remove_Map"];
							[[list objectAtIndex:0] addObject:@"item_Map_Import"];
							[table reloadData];
							title 	= @"Import finishd";
							message = [NSString stringWithFormat:@"Map %@ imported",Name];
						}
						break;
					case 1:
						NSLog(@"  in import Route function");
						if([manager fileExistsAtPath:defaultRoute]){
							[manager copyItemAtPath:defaultRoute toPath:[NSString stringWithFormat:@"/var/mobile/Media/Maps/%@",Name] error:nil];
							[[list objectAtIndex:1] removeLastObject];
							[[list objectAtIndex:1] removeLastObject];
							[[list objectAtIndex:1] addObject:Name];
							[[list objectAtIndex:1] addObject:@"Remove_Route"];
							[[list objectAtIndex:1] addObject:@"item_Route_Import"];
							[table reloadData];
							title 	= @"Import finishd";
							message = [NSString stringWithFormat:@"Route %@ imported",Name];
						}
						break;
					case 2:
						NSLog(@"  in import Bookmark function");
						if ([manager fileExistsAtPath:defaultBookmark]){
							[manager copyItemAtPath:defaultBookmark toPath:[NSString stringWithFormat:@"/var/mobile/Media/Maps/%@",Name ] error:nil];
							[[list objectAtIndex:2] removeLastObject];
							[[list objectAtIndex:2] removeLastObject];
							[[list objectAtIndex:2] addObject:Name];
							[[list objectAtIndex:2] addObject:@"Remove_Bookmark"];
							[[list objectAtIndex:2] addObject:@"item_Bookmarks_Import"];
							[table reloadData];	
							title 	= @"Import finishd";
							message = [NSString stringWithFormat:@"Bookmark %@ imported",Name];
						}
						break;
				}
			}
		}
	}
	else if (alertView == confirmAlert){
		NSLog(@"    Confirm alert");
		Name = [[list objectAtIndex:section] objectAtIndex:row];
		switch(section){
			case 0:
				NSLog(@"    Confirm Map function");
				NSString *folder = [NSString stringWithFormat:@"/var/mobile/Media/Maps/%@", Name ]; 
				if([manager fileExistsAtPath:defaultMapTiles]){
					[manager removeItemAtPath:defaultMapTiles error:nil];
				}
				if([manager fileExistsAtPath:defaultMapPoint]){
					[manager removeItemAtPath:defaultMapPoint error:nil];
				}
				if(![Name isEqualToString:@"Remove_Map"]){
					NSLog([NSString stringWithFormat:@"    Confirm Using Map %@ to Google Maps", Name]);
					NSLog([NSString stringWithFormat:@"    Choose method = %i", buttonIndex]);
					if(buttonIndex == 1){
						NSLog(@"        Copy method");
						[manager copyItemAtPath:[folder stringByAppendingPathComponent:MapTiles] toPath:defaultMapTiles error:nil];

					}
					/*
					if([Name canBeConvertedToEncoding:NSASCIIStringEncoding]){
						NSLog(@"ASCII String");
						if ([Name length] > 4){
							NSLog(@"%@",[Name substringWithRange:NSMakeRange(0,4)]);
							[self setApplicationBadgeString:[Name substringWithRange:NSMakeRange(0,4)]];
						}
						else{
							[self setApplicationBadgeString:Name];
						}
					}
					else{
						NSLog(@"Not a ASCII String");
						if ([Name length] > 2){
							NSLog(@"%@",[Name substringWithRange:NSMakeRange(0,2)]);
							[self setApplicationBadgeString:[Name substringWithRange:NSMakeRange(0,2)]];
						}
						else{
							[self setApplicationBadgeString:Name];
						}
					}
					*/
					[manager copyItemAtPath:[folder stringByAppendingPathComponent:Plist] toPath:defaultMapPoint error:nil];
					[[a initWithTitle:NSLocalizedString(@"Processing_Map",nil)
						message:NSLocalizedString(@"Process_Finish_Message",nil)
						delegate:self
						cancelButtonTitle:NSLocalizedString(@"Continue",@"Stay in Atlas")
						otherButtonTitles:NSLocalizedString(@"Launch_Maps",@"Launch google maps"),nil] show];
				}
				else{
					NSLog(@"    Confirm Remove Cache");
					[[a initWithTitle:NSLocalizedString(@"Remove_Map",nil)
						message:NSLocalizedString(@"Process_Finish",nil)
						delegate:self 
						cancelButtonTitle:NSLocalizedString(@"Ok",@"Ok") 
						otherButtonTitles:nil] show];
				}
				break;
			case 1:
				NSLog(@"    Confirm Route function");
				if([manager fileExistsAtPath:defaultRoute]){
					[manager removeItemAtPath:defaultRoute error:nil];
				}
				if (![Name isEqualToString:@"Remove_Route"]){
					NSLog([NSString stringWithFormat:@"    Confirm Copy Route %@ to Google Maps", Name ]);
					[manager copyItemAtPath:[NSString stringWithFormat:@"/var/mobile/Media/Maps/%@",Name ] toPath:defaultRoute error:nil];
					[[a initWithTitle:NSLocalizedString(@"Processing_Route",nil) 
						message:NSLocalizedString(@"Process_Finish_Message",nil) 
						delegate:self 
						cancelButtonTitle:NSLocalizedString(@"Continue",nil) 
						otherButtonTitles:NSLocalizedString(@"Launch_Maps",@"Launch google maps") , nil] show];
				}
				else{
					NSLog(@"    Show Remove Route");
					[[a initWithTitle:NSLocalizedString(@"Remove_Route",nil) 
						message:NSLocalizedString(@"Process_Finish",nil) 
						delegate:self 
						cancelButtonTitle:NSLocalizedString(@"Ok",@"Ok") 
						otherButtonTitles:nil] show];
				}
				break;
			case 2:
				if([manager fileExistsAtPath:defaultBookmark])
				{
					NSLog(@"    Remove Bookmark");
					[manager removeItemAtPath:defaultBookmark error:nil];
				}
				if(![Name isEqualToString:@"Remove_Bookmark"]){
					NSLog(@"    Copy Bookmark");
					[manager copyItemAtPath:[NSString stringWithFormat:@"/var/mobile/Media/Maps/%@",Name ] toPath:defaultBookmark error:nil];
					[[a initWithTitle: NSLocalizedString(@"Processing_Bookmarks",@"Show user , command process") 
						message: NSLocalizedString(@"Process_Finish_Message",@"Let User choose where to go ")
						delegate: self 
						cancelButtonTitle: NSLocalizedString(@"Continue",@"Continue") 
						otherButtonTitles: NSLocalizedString(@"Launch_Maps",@"Launch google maps") ,nil] show];
				}
				else{
					NSLog(@"    Show Remove Bookmark");
					[[a initWithTitle:NSLocalizedString(@"Remove_Bookmark",@"Remove Bookmark") 
						message:NSLocalizedString(@"Process_Finish",@"Process_Finish") 
						delegate:self 
						cancelButtonTitle:NSLocalizedString(@"Ok",@"Ok") 
						otherButtonTitles:nil] show];
				}
				break;
		}
	}
	else {
		// buttonIndex != 0 which means it must be Launch google Maps or Launch Safari
		switch(section){
			case 3:// Infos section , launch Safari
				NSLog(@" Open Safari");
				[self openURL:[NSURL URLWithString :NSLocalizedString(@"Localizable_Web_Site",@"http://code.google.com/p/iphoneofflinemap/")]];
				break;
			default:
				[self launchApplicationWithIdentifier:@"com.apple.Maps" suspended:NO];	
				break;
		}
	}
	[alertView release];
	return;
}

- (id) init{
	NSLog(@"[%@ init]", [self class]);
	self = [super init];
	manager = [NSFileManager defaultManager];
	return self;
}

- (void) applicationDidFinishLaunching: (id) unused{

	//NSLog(@"[%@ applicationDidFinishLaunching:%@]", [self class], unused);
    window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
	CGRect boundrect = [[UIScreen mainScreen] bounds];
	CGRect navrect = CGRectMake(0.0f,0.0f,boundrect.size.width,64.0f);
	CGRect tablerect = CGRectMake(0.0f,64.0f,boundrect.size.width,(boundrect.size.height - 64.0f));
    /* Create a main view */
	deviceInfo = [[UIDevice currentDevice] systemVersion];
    mainView = [[UIView alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
    navbar =  [[UINavigationBar alloc] initWithFrame:navrect];
	//editButtom = [[UIBarButtomItem alloc] initWithTitle:@"Edit" style:UIBarButtonItemStylePlain target:self action:@selector(EditAction:) ];
	navtitle = [[UINavigationItem alloc] initWithTitle: NSLocalizedString(@"App_Title",@"OfflineMap / Atlas :P")];
	navtitle.rightBarButtonItem=[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit  target:self  action:@selector(startEditing)] autorelease];
	//[navtitle setRightBarButtonItem: editButtom animated:YES];
	[navbar setDelegate: self];
    [navbar pushNavigationItem: navtitle animated: true];
    [mainView addSubview:navbar];// UITableViewStylePlain UITableViewStyleGrouped
	table = [[UITableView alloc] initWithFrame:tablerect style: UITableViewStyleGrouped];
	[mainView addSubview: table];
	[table setDataSource:self];
    [table setDelegate:self];
    [table setEditing:NO animated:YES];
    table.allowsSelectionDuringEditing = YES;
	[table setAllowsSelectionDuringEditing:YES];
    //[table setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    NSLog([NSString stringWithFormat:@"Atlas Run on FW %@ ", deviceInfo]);
	NSLog(@"%@ is %@ / %@",[[UIDevice currentDevice] name] , [[UIDevice currentDevice] model] , [[UIDevice currentDevice] localizedModel]);
	if ([deviceInfo isEqualToString: @"2.2"] || [deviceInfo hasPrefix:@"3"] || [deviceInfo hasPrefix:@"4"])
		defaultRoute = defaultRoute_2_2;
	else	
		defaultRoute = defaultRoute_2_1;
		
	if([deviceInfo hasPrefix:@"3.1"] || [deviceInfo hasPrefix:@"3.2"] || [deviceInfo hasPrefix:@"4"])
	{
		NSLog(@"System is Upto 3.1, and the defaultMapTiles is place at /var/mobile/Library/Caches/Maps/MapTiles/MapTiles.sqlitedb");
		defaultMapTiles = defaultMapTiles_new;
	}
	else
	{
		defaultMapTiles = defaultMapTiles_old;
	}
	//NSLog([NSString stringWithFormat:@"Default Route is :%@",defaultRoute ]);

	if(![manager fileExistsAtPath:HOME]){
		NSLog(@"Map root folder not exists, try to make one.");
		[manager createDirectoryAtPath:HOME attributes: nil];
		alert = [UIAlertView alloc];
		[[alert initWithTitle: 	NSLocalizedString(@"Root_Not_Exists",@"Maps folder not exists") 
				message: 		NSLocalizedString(@"Root_Not_Exists_Message",@"Make root folder for user") 
				delegate: self 
				cancelButtonTitle: NSLocalizedString(@"Ok",@"Ok") 
				otherButtonTitles:nil] show];
	}
	/* Setup window */
	[window makeKeyAndVisible];
	[window addSubview: mainView];
	list = [[NSMutableArray alloc] init];
	[list addObject:[[NSMutableArray alloc] init]];
	[list addObject:[[NSMutableArray alloc] init]];
	[list addObject:[[NSMutableArray alloc] init]];
	[list addObject:[[NSMutableArray alloc] init]];
	NSMutableArray *maps = [[NSMutableArray alloc] init];
	NSLog(@"Setup TableView Data.");
	[maps addObjectsFromArray:[manager contentsOfDirectoryAtPath:HOME error:NULL]];
	NSLog(@"Trying each item in MAP Folder");
	for (NSString *path in maps) {
	//check if list is a folder...
		//NSLog([NSString stringWithFormat:@"Check item : %@", path]);
		BOOL isDir;
		if ([manager fileExistsAtPath: [NSString stringWithFormat:@"/var/mobile/Media/Maps/%@",path] isDirectory: &isDir ] && isDir){
			// if path is a folder
			NSString *folder = [NSString stringWithFormat:@"/var/mobile/Media/Maps/%@",path];
			if([manager fileExistsAtPath:[folder stringByAppendingPathComponent:MapTiles]] && [manager fileExistsAtPath:[folder stringByAppendingPathComponent:Plist]]){
				NSLog([NSString stringWithFormat:@" %@ is a Map folder\n", path]);
				///*
					NSMutableArray *bundle = [[NSMutableArray alloc] init];
					[bundle addObjectsFromArray:[manager contentsOfDirectoryAtPath:[NSString stringWithFormat:@"/var/mobile/Media/Maps/%@",path ] error:NULL]];
					for (NSString * bundle_item in bundle){
						//NSLog([NSString stringWithFormat:@"Check item %@ in %@ folder",bundle_item , path ]);
						if ([bundle_item isEqualToString:MapTiles] || [bundle_item isEqualToString:Plist] || [bundle_item isEqualToString:@"Badget"]){
							//NSLog([NSString stringWithFormat:@"ignore item %@ in %@ folder",bundle_item , path  ]);
						}
						else{
							NSLog([NSString stringWithFormat:@"require add item %@ into list",bundle_item ]);
						}
					}
				//*/
				[[list objectAtIndex: 0 ] addObject: path];
			}
			else{
				NSLog([NSString stringWithFormat:@"%@ is not a Map folder", path]);
			}
		}
		else{ // if path is a file
			NSDictionary * plist = [NSMutableDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"/var/mobile/Media/Maps/%@",path]];
			NSString *description = [plist description];
			NSString *checker = [description substringWithRange: NSMakeRange(6,9)];
			if ([checker isEqualToString:@"Bookmarks"])
			{
				NSLog([NSString stringWithFormat:@" %@ is a Bookmark file", path]);
				[[list objectAtIndex: 2] addObject: path];
			}
			else
			{
				if([deviceInfo isEqualToString:@"2.2"] || [deviceInfo hasPrefix:@"3"] || [deviceInfo hasPrefix:@"4"]){ //check route is 2.2 or not?
					if ([checker isEqualToString:@"Direction"]){
						[[list objectAtIndex: 1] addObject: path];
						NSLog([NSString stringWithFormat:@" %@ is a usable Route file", path]);
					}
					else
						NSLog([NSString stringWithFormat:@" %@ is not a 2.2 Route file", path]);
				}
				else{
					if ([checker isEqualToString:@"Direction"])
						NSLog([NSString stringWithFormat:@" %@ is not a 2.1 Route file", path]);
					else{
						[[list objectAtIndex: 1] addObject: path];
						NSLog([NSString stringWithFormat:@" %@ is a usable Route file", path]);
					}
				}
			}
		}
    }
	[[list objectAtIndex:0] addObject: @"Remove_Map"];
	[[list objectAtIndex:0] addObject: @"item_Map_Import"];
	[[list objectAtIndex:1] addObject: @"Remove_Route"];
	[[list objectAtIndex:1] addObject: @"item_Route_Import"];
	[[list objectAtIndex:2] addObject: @"Remove_Bookmark"];
	[[list objectAtIndex:2] addObject: @"item_Bookmarks_Import"];
	[[list objectAtIndex:3] addObject: @"Instructions"];
	[[list objectAtIndex:3] addObject: @"Launch_Safari_Message"];
	
	[table reloadData];
}

@end
